package class07;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Auther: xw
 * @Create: 2022/3/29 10:07
 * @Description: 给你二叉树的根节点 root ，返回其节点值 自底向上的层序遍历 。
 *                          （即按从叶子节点所在层到根节点所在的层，逐层从左向右遍历）
 *                          https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
 */
public class BinaryTreeLevelOrder {
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans  = new LinkedList<>();
        if(root == null){
            return ans;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            List<Integer> cur = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                cur.add(node.val);
                if(node.left != null){
                    queue.add(node.left);
                }
                if(node.right != null){
                    queue.add(node.right);
                }
            }
            ans.add(0,cur);
        }
        return ans;
    }
}
